home *** CD-ROM | disk | FTP | other *** search
- Path: surfnet.nl!sun4nl!xs4all!falstaff
- From: falstaff@xs4all.nl (Falstaff)
- Newsgroups: comp.lang.c
- Subject: Re: Calling a Function Twice from a printf statement.
- Date: 4 Mar 1996 11:10:24 GMT
- Organization: XS4ALL, networking for the masses
- Message-ID: <4hej30$se4@news.xs4all.nl>
- References: <4he6q9$6r6@newsbf02.news.aol.com>
- NNTP-Posting-Host: xs1.xs4all.nl
- X-Newsreader: NN version 6.5.0 #666 (NOV)
-
- razine@aol.com (Razine) writes:
-
- >I am trying to call a function twice from my program on the same printf
- >line and have run into a small problem. i was wondering if someone can
- >explain how to fix it.
-
-
- >void main(void) {
-
- > printf("First Number is %d , the Second s %d \n",num(0),num(1));
-
- >}
-
- >int num(int index) {
- > int return_number;
- >
- > switch(index) {
- > case 0 : return_number=0;
- > case 1 : return_number=1;
- > }
- > return(return_number);
- >}
- >Now with this function, the printf line will display 0 for the first one
- >and garbage for the second one.. I then thought if I made the variable
- >return_number a static variable it would have fixed it but then when i
- >made the change the printf line would give me zero for both of them. Any
- >ideas?
-
- Hmmm, a former Pascal programmer?
-
- How about this:
-
- int num(int index)
- { int r=-1; /* initialized just to be sure that something valid
- is returned when index does not match any case */
- switch(index)
- {
- case 0:
- r=0;
- break; /* you forgot this one */
- case 1:
- r=1;
- break; /* no break needed here, but included so that things
- don't go wrong when more cases are added */
- }
- return r; /* no braces needed: return is NOT a function call */
- }
-
- No need for static variables in this program. Generally, you can't
- be certain which function call is evaluated first, so something like
- this is a Bad Thing (assuming the same printf statement in main()):
-
- int num(int index)
- { static int r=0;
-
- r=r+index;
-
- return r;
- }
-
- If the first call to num() is done first, printf prints
- "First Number is 0 , the Second s 1 ", but when the second call
- is evaluated first, the result is "First Number is 1 , the Second s 1 "
-
- Frank
- --
- The famous GIICM now on line: http://www.xs4all.nl/~falstaff/GIICM.html
- ------------------------------------------------------------------------
- Frank A. Vorstenbosch +31-(70)-355 5241 falstaff@xs4all.nl
-